using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using GrrrControls;
using SAGE.Agent;

namespace SAGE
{
  public class Simulation
  {
    #region Static Members

    private static World _world;
    private static Thread _thread = null;
    private static DateTime _startTime;
    private static bool _running;

    private static readonly int _THREAD_SLEEP = 30;

    #endregion

    #region Properties

    public static World World
    {
      get { return Simulation._world; }
    }

    #endregion

    #region Static Methods

    public static void Initialize(World world)
    {
      _world = world;
    }

    public static bool Start()
    {
      if (_thread == null && _world != null)
      {
        _thread = new Thread(SimulationLoop);
        _thread.Start();
        return true;
      }
      else
      {
        return false;
      }
    }

    private static void SimulationLoop()
    {
      _startTime = DateTime.Now;
      _running = true;

      GrrrControl.RedrawOften(true);
      GrrrControl.SetStatus("Simulation started!");

      while (_running)
      {
        foreach (IAgent agent in _world.Agents)
        {
          agent.Update(GetGameTime(), _world.Physics);
        }
        Thread.Sleep(_THREAD_SLEEP);
      }
    }

    #endregion

    #region Helper Methods

    private static TimeSpan GetGameTime()
    {
      TimeSpan timeSpan = (DateTime.Now - _startTime);
      return timeSpan;
    }

    #endregion


  }
}
